﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;

namespace DAL.Gateway
{
    public class SqLiteDb : GDatos
    {
        static readonly System.Collections.Hashtable ColComandos = new System.Collections.Hashtable();

        public override string CadenaConexion
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        protected override System.Data.IDbConnection CrearConexion(string cadena)
        {
            return new SQLiteConnection(cadena);
        }

        protected override System.Data.IDbCommand Comando(string procedimientoAlmacenado)
        {
            SQLiteCommand com;
            if (ColComandos.Contains(procedimientoAlmacenado))
                com = (SQLiteCommand)ColComandos[procedimientoAlmacenado];
            else
            {
                var con2 = new SQLiteConnection(CadenaConexion);
                con2.Open();

                com = new SQLiteCommand(procedimientoAlmacenado, con2)
                {
                    CommandType = System.Data.CommandType.StoredProcedure
                };
                //SQLiteCommandBuilder.DeriveParameters(com);
                con2.Close();
                con2.Dispose();
                ColComandos.Add(procedimientoAlmacenado, com);
            }
            com.Connection = (SQLiteConnection)Conexion;
            com.Transaction = (SQLiteTransaction)MTransaccion;
            return com;
        }

        protected override System.Data.IDbCommand ComandoSql(string comandoSql)
        {
            return new SQLiteCommand(comandoSql, (SQLiteConnection)Conexion, (SQLiteTransaction)MTransaccion);
        }

        protected override System.Data.IDataAdapter CrearDataAdapter(string procedimientoAlmacenado, params object[] args)
        {
            var da = new SQLiteDataAdapter((SQLiteCommand)Comando(procedimientoAlmacenado));
            if (args.Length != 0)
                CargarParametros(da.SelectCommand, args);
            return da;
        }

        protected override System.Data.IDataAdapter CrearDataAdapterSql(string comandoSql)
        {
            var da = new SQLiteDataAdapter((SQLiteCommand)ComandoSql(comandoSql));
            return da;
        }

        protected override void CargarParametros(System.Data.IDbCommand com, object[] args)
        {
            for (var i = 0; i < com.Parameters.Count; i++)
            {
                var p = (SQLiteParameter)com.Parameters[i];
                p.Value = i <= args.Length ? args[i] : null;
            }
        }
   
    }
}
